<script setup>
import { ref } from 'vue'
import {
  pageQueryQuestionSubmit,
  deleteQuestionSubmit
} from '@/api/question.js'
import { Message } from '@arco-design/web-vue'
import { useUserStore } from '@/stores/index.js'
import router from '@/router/index.js'

const userStore = useUserStore()
const isAdmin = userStore.auth === 'admin' // 假设 admin 为管理员权限

const pageForm = ref({
  title: '',
  submitLanguage: '',
  judgeInfo: '',
  userId: '',
  submitStatus: '',
  beginTime: '',
  endTime: '',
  currentPage: 1,
  pageSize: 10
})
const pageFormRef = ref()
const total = ref(0)
const createTime = ref()
const tableLoading = ref(false)
const tableData = ref([])

const columns = [
  {
    title: '题目标题',
    dataIndex: 'title',
    ellipsis: true,
    tooltip: true,
    slotName: 'titleSlot'
  },
  {
    title: '编程语言',
    dataIndex: 'submitLanguage',
    ellipsis: true,
    tooltip: true,
    width: 100
  },
  {
    title: '判题信息',
    dataIndex: 'judgeInfo',
    ellipsis: true,
    tooltip: true,
    width: 300,
    slotName: 'judgeInfoSlot',
    children: [
      {
        title: '判题结果',
        dataIndex: 'judgeInfo.message',
        ellipsis: true,
        tooltip: true,
        width: 120
      },
      {
        title: '消耗时间(ms)',
        dataIndex: 'judgeInfo.time',
        ellipsis: true,
        tooltip: true,
        width: 120
      },
      {
        title: '消耗内存(B)',
        dataIndex: 'judgeInfo.memory',
        ellipsis: true,
        tooltip: true,
        width: 120
      }
    ]
  },
  {
    title: '判题状态',
    dataIndex: 'submitStatus',
    ellipsis: true,
    tooltip: true,
    width: 100,
    slotName: 'submitStatusSlot'
  },
  {
    title: '答题用户',
    dataIndex: 'userId',
    ellipsis: true,
    tooltip: true,
    width: 100
  },
  {
    title: '答题时间',
    dataIndex: 'createTime',
    width: 180
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    width: 180
  },
  {
    title: '操作',
    align: 'center',
    dataIndex: 'action',
    slotName: 'optional'
  }
]

const selectedKeys = ref([])
const rowSelection = ref({
  type: 'checkbox',
  showCheckedAll: true,
  onlyCurrent: false
})

// 重置查询表单
const resetPageForm = () => {
  pageFormRef.value.resetFields()
  createTime.value = ''
}

// 分页处理
const pageChange = (currentPage) => {
  pageForm.value.currentPage = currentPage
  submitPageForm()
}

const pageSizeChange = (pageSize) => {
  pageForm.value.pageSize = pageSize
  submitPageForm()
}

// 查询答题记录
const submitPageForm = (flag) => {
  if (flag === 1) {
    pageForm.value.currentPage = 1
  }
  if (createTime.value) {
    function convertToChinaTime(utcTimeString) {
      const utcDate = new Date(utcTimeString)
      utcDate.setHours(utcDate.getHours() + 8)
      return utcDate.toISOString()
    }

    pageForm.value.beginTime = convertToChinaTime(createTime.value[0])
    pageForm.value.endTime = convertToChinaTime(createTime.value[1])
  }
  tableLoading.value = true
  pageQueryQuestionSubmit(pageForm.value)
    .then(res => {
      if (res.data.code === 1) {
        tableData.value = res.data.data.records
        total.value = Number(res.data.data.total)
      } else {
        Message.error(res.data.message || '查询答题记录失败')
      }
    })
    .catch(error => {
      console.error(error)
      Message.error('查询答题记录失败')
    })
    .finally(() => {
      tableLoading.value = false
    })
}
submitPageForm()

// 删除答题记录
const handleDelete = () => {
  const selectedIds = selectedKeys.value
  if (selectedIds.length === 0) {
    Message.warning('请选择要删除的答题记录')
    return
  }
  deleteQuestionSubmit(selectedIds)
    .then(res => {
      if (res.data.code === 1) {
        Message.success('删除成功')
        submitPageForm()
      } else {
        Message.error(res.data.message || '删除失败')
      }
    })
    .catch(error => {
      console.error(error)
      Message.error('删除失败')
    })
}

// 获取答题记录详情
const handleViewDetail = (id) => {
  router.push(`/answer/detail/${id}`)
}
</script>

<template>
  <div id="answer-record-manager">
    <div class="card">
      <div class="set-container">
        <div class="select-container">
          <a-form :model="pageForm" layout="inline" ref="pageFormRef">
            <a-form-item label="题目标题" field="title">
              <a-input v-model="pageForm.title" placeholder="请输入题目标题"></a-input>
            </a-form-item>
            <a-form-item label="编程语言" field="submitLanguage">
              <a-input v-model="pageForm.submitLanguage" placeholder="请输入编程语言"></a-input>
            </a-form-item>
            <a-form-item label="判题结果" field="judgeInfo">
              <a-input v-model="pageForm.judgeInfo" placeholder="请输入判题结果"></a-input>
            </a-form-item>
            <a-form-item v-if="isAdmin" label="答题用户" field="userId">
              <a-input v-model="pageForm.userId" placeholder="请输入答题用户id"></a-input>
            </a-form-item>
            <a-form-item label="判题状态" field="submitStatus">
              <a-select v-model="pageForm.submitStatus" placeholder="请选择判题状态">
                <a-option value="0">待判题</a-option>
                <a-option value="1">判题中</a-option>
                <a-option value="2">成功</a-option>
                <a-option value="3">失败</a-option>
              </a-select>
            </a-form-item>
            <a-form-item label="答题时间" field="beginTime">
              <a-range-picker
                showTime
                v-model="createTime"
                :time-picker-props="{ defaultValue: ['00:00:00', '00:00:00'] }"
                :format="'YYYY-MM-DDTHH:mm:ss'"
                style="width: 380px;"
              />
            </a-form-item>
            <div class="button-container">
              <div class="left">
                <a-form-item>
                  <a-button type="primary" class="btn" @click="submitPageForm(1)">查询</a-button>
                  <a-button type="outline" class="btn" @click="resetPageForm">重置</a-button>
                </a-form-item>
              </div>
              <div class="right">
                <a-popconfirm
                  v-if="isAdmin"
                  content="确定要删除选中的答题记录吗？"
                  @ok="handleDelete"
                  position="br"
                >
                  <a-button type="primary" status="danger" class="btn">删除</a-button>
                </a-popconfirm>
              </div>
            </div>
          </a-form>
        </div>
      </div>
      <a-divider>答题记录</a-divider>
      <div class="table-container">
        <a-table
          stripe
          size="medium"
          :scroll="{ x: 1000 }"
          :loading="tableLoading"
          :pagination="false"
          row-key="id"
          :row-selection="rowSelection"
          v-model:selectedKeys="selectedKeys"
          :columns="columns"
          :data="tableData"
        >
          <template #titleSlot="{ record }">
            <span @click="router.push(`/question/${record.questionId}`)" style="font-size: 16px; cursor: pointer;">{{ record.title }}</span>
          </template>
          <template #submitStatusSlot="{ record }">
            <a-tag v-if="record.submitStatus === 0" color="blue">待判题</a-tag>
            <a-tag v-if="record.submitStatus === 1" color="orange">判题中</a-tag>
            <a-tag v-if="record.submitStatus === 2" color="green">成功</a-tag>
            <a-tag v-if="record.submitStatus === 3" color="red">失败</a-tag>
          </template>
          <template #optional="{ record }">
            <a-button type="text" @click="handleViewDetail(record.id)">详情</a-button>
          </template>
        </a-table>
      </div>
      <a-divider />
      <a-pagination
        show-total
        show-jumper
        show-page-size
        size="small"
        :total="total"
        :default-page-size="12"
        :current="pageForm.currentPage"
        :page-size="pageForm.pageSize"
        @change="pageChange"
        @page-size-change="pageSizeChange"
      />
    </div>
  </div>
</template>

<style scoped>
.card {
  margin-top: 20px;
  background-color: var(--color-bg-1);
  border: 1px solid var(--color-neutral-1);
  padding: 16px;
}

.set-container {
  position: relative;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.table-container {
  min-height: 60vh;
}

.select-container .btn, .button-container .btn {
  margin-right: 5px;
}

.button-container {
  display: flex;
  justify-content: space-between;
}

.button-container .right {
  position: absolute;
  right: 0;
}
</style>
